package org.example;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;

import java.sql.*;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.Executor;

public class RedisConnection implements Connection {
    private Jedis connection;
    private int index;
    private Properties properties;

    public RedisConnection(String url, Properties info) throws SQLException {
        this.connection = this.getConnection(url, info);
        this.properties = info;
    }

    public Jedis getConnection() {
        return connection;
    }

    private Jedis getConnection(String url, Properties info) throws SQLException {
        //jdbc:redis://{hostname}:{port}/{dbIndex}
        if(Objects.isNull(url) || !url.startsWith("jdbc:redis://")){
            throw new SQLException("URL无效，请以jdbc:redis://开头");
        }
        String hostIpIndex = url.substring(13);
        String[] split = hostIpIndex.split(":");
        String ip = split[0];
        String[] temp = split[1].split("/");
        String port = temp[0];
        String indexStr = temp[1];
        if(indexStr.contains("?")){
            indexStr = indexStr.substring(0, indexStr.indexOf("?"));
        }
        this.index = Integer.parseInt(indexStr);

        Jedis jedis = new Jedis(ip, Integer.parseInt(port));
        jedis.connect();
        jedis.select(this.index);
        return jedis;
    }

    @Override
    public Statement createStatement() throws SQLException {
        return new RedisStatement(this, this.connection);
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return null;
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return null;
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return null;
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {

    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return true;
    }

    @Override
    public void commit() throws SQLException {

    }

    @Override
    public void rollback() throws SQLException {

    }

    @Override
    public void close() throws SQLException {
        this.connection.close();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return !this.connection.isConnected();
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return new RedisDatabaseMetadata(this, ""+this.index);
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {

    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return false;
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {

    }

    @Override
    public String getCatalog() throws SQLException {
        return null;
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {

    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return 0;
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return null;
    }

    @Override
    public void clearWarnings() throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return this.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return this.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return this.prepareCall(sql);
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return null;
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {

    }

    @Override
    public void setHoldability(int holdability) throws SQLException {

    }

    @Override
    public int getHoldability() throws SQLException {
        return 1;
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return null;
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return null;
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {

    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return this.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return this.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return this.prepareCall(sql);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return this.prepareStatement(sql);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return this.prepareStatement(sql);
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return this.prepareStatement(sql);
    }

    @Override
    public Clob createClob() throws SQLException {
        return null;
    }

    @Override
    public Blob createBlob() throws SQLException {
        return null;
    }

    @Override
    public NClob createNClob() throws SQLException {
        return null;
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return null;
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        if (this.isClosed()) {
            return false;
        }
        // TODO 超时时间
        try {
            this.connection.sendCommand(Protocol.Command.PING);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {
        this.properties.put(name, value);
    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {
        this.properties.putAll(properties);
    }

    @Override
    public String getClientInfo(String name) throws SQLException {

        String property = this.properties.getProperty(name);
        property = property == null ? "" : property;
        return property;
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return this.properties;
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        throw new SQLFeatureNotSupportedException("createArrayOf not implemented");
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        throw new SQLFeatureNotSupportedException("createStruct not implemented");
    }

    @Override
    public void setSchema(String schema) throws SQLException {
        synchronized (RedisConnection.class) {

            this.connection.select(Integer.parseInt(schema));

            this.index = Integer.parseInt(schema);
        }
    }

    @Override
    public String getSchema() throws SQLException {
        synchronized (RedisConnection.class) {
            return ""+this.index;
        }
    }

    @Override
    public void abort(Executor executor) throws SQLException {

    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {

    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return 0;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        try {
            return iface.cast(this);
        } catch (ClassCastException cce) {
            throw new SQLException("Unable to unwrap to " + iface);
        }
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return iface.isInstance(this);
    }


}
